package no.ntnu.idi.deid.patternmatching.search.dictionary.medicalcodes;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;

import no.ntnu.idi.deid.config.FilePaths;
import no.ntnu.idi.deid.documentunits.Token;
import no.ntnu.idi.deid.searchresultunits.CategoryTag;
import no.ntnu.idi.deid.searchresultunits.Tag;

public class NCRP_codes {
	
	private static Map<String, String> NCRPCodes;
	
	private NCRP_codes(){
		if(NCRPCodes==null){try {
			readAndMakeNCRPCodes();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}}
	}
	
	public static CategoryTag searchNCRPCode(Token t) {
		new NCRP_codes();
		if(NCRPCodes.containsKey(t.getStripped())){
			CategoryTag tag = new CategoryTag(Tag.NCRP);
			tag.setValues(t.getStripped(), NCRPCodes.get(t.getStripped()));
			return tag;
		}
		return null;
	}
	
	public static CategoryTag searchExactDescription(String str) {
		new NCRP_codes();
		Iterator<Entry<String, String>> it = NCRPCodes.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			if(entry.getValue().equals(str.trim())){
				CategoryTag tag = new CategoryTag(Tag.NCRP);
				tag.setValues(entry.getKey(), entry.getValue());
				return tag;
			}
		}
		return null;
	}
	
	private void readAndMakeNCRPCodes() throws FileNotFoundException{
		NCRPCodes = new HashMap<String,String>();
		Scanner sc = new Scanner(new File(FilePaths.getNCRPCodesPath()));
		System.out.println(FilePaths.getNCRPCodesPath());
		while(sc.hasNext()){
			String[] split= sc.nextLine().split("\\$\\$\\$");
			if(split.length==2){handleLine(split);}
		}
		sc.close();
	}
	
	private void handleLine(String[] split){
//		testCounter++;
		if(split[0].length()!=5){}
		NCRPCodes.put(split[0].trim(), split[1].trim());
	}
	

}
